import { FILECACHE } from '../config.js'

const state = {
	cache: uni.getStorageSync(FILECACHE) || [] //缓存列表
}

const getters = {
	get (state) {
		return state.cache
	}
}

const mutations = {
	set (state, cache) {
		state.cache = cache
		uni.setStorageSync(FILECACHE, state.cache)
	}
}

const actions = {
	add ({state, commit}, cache) {
		const caches = [...state.cache]
		const index = caches.findIndex(cache => cache.id == cache.id)
		index > -1 ? caches[index] = cache : caches.push(cache)
		commit('set', caches)
	},
	remove ({state, commit}, id) {
		const caches = [...state.cache]
		const index = caches.findIndex(cache => cache.id == id)
		if ( index > -1 ) {
			const src = plus.io.convertLocalFileSystemURL(caches[index].src);
			const file = plus.android.newObject('java.io.File', src);
			if ( plus.android.invoke(file, 'exists') ) {
				plus.android.invoke(file, 'delete')
			}
			caches.splice(index, 1);
		}
		commit('set', caches)
	},
	clear ({commit}, type) {
		const caches = [...state.cache]
		commit('set', caches.filter(cache => cache.type != type))
	}
}

export default {
    namespaced: true,
    state,
    getters,
    mutations,
	actions
}